package groups

import (
	"context"
	"fmt"
	"server/chat_room_server/model/entity"

	"server/chat_room_server/internal/svc"
	"server/chat_room_server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GroupsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGroupsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GroupsLogic {
	return &GroupsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GroupsLogic) Groups(req *types.GroupsReq) (resp *types.GroupsResp, err error) {
	// todo: add your logic here and delete this line
	groupId := req.GroupId
	db := l.svcCtx.DB
	var groups []entity.Group
	if groupId != 0 {
		db.Where(fmt.Sprintf(" group_id = %v", groupId)).Find(&groups)
	} else {
		db.Find(&groups)
	}

	var groupId1 int64
	var groupName string
	var friends []types.FiendsResp

	for i := range groups {
		group := groups[i]
		id := group.ID
		var userGroups []entity.UserGroup
		db.Where(" group_id = ?", id).Find(&userGroups)
		var userIds []uint
		for i2 := range userGroups {
			userGroup := userGroups[i2]
			userId := userGroup.UserId
			userIds = append(userIds, userId)
		}
		var users []entity.User
		db.Find(&users, userIds)

		var fiendsResps []types.FiendsResp

		for i2 := range users {
			user := users[i2]
			fiendsResp := types.FiendsResp{
				UserId:   user.UserId,
				UserName: user.Name,
			}
			fiendsResps = append(fiendsResps, fiendsResp)
		}
		groupId1 = group.GroupId
		groupName = group.Name
		friends = fiendsResps
		break
	}

	return &types.GroupsResp{
		GroupName:   groupName,
		GroupId:     groupId1,
		FiendsResps: friends,
	}, nil
}
